package com.ecoolex.hotel.saas.core.config;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ecoolex.framework.common.util.Check;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ecoolex.hotel.saas.core.manager.StoreWeixinConfigManager;
import com.ecoolex.hotel.saas.core.pojo.WeiXinProperties;
import com.ecoolex.hotel.saas.entity.StoreWeixinConfig;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.EntPayService;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.EntPayServiceImpl;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;

@Configuration
public class WxPayServiceInitializer {

	@Autowired
	private WeiXinProperties weiXinProperties;
	
	@Autowired
	private StoreWeixinConfigManager storeWeixinConfigManager;

//	@Bean
//	public WxPayConfig wxPayConfig() {
//		WxPayConfig payConfig = new WxPayConfig();
//		payConfig.setAppId(weiXinProperties.getAppId());
//		payConfig.setMchId(weiXinProperties.getMchId());
//		payConfig.setMchKey(weiXinProperties.getMchKey());
//		payConfig.setNotifyUrl(weiXinProperties.getNotifyUrl());
//		payConfig.setKeyPath(weiXinProperties.getKeyPath());
////		payConfig.setTradeType("JSAPI");
//		payConfig.setSignType("MD5");
//		payConfig.setIfSaveApiData(true);
//		return payConfig;
//	}

	@Bean
	public WxPayService wxPayService() {
		List<StoreWeixinConfig> list = storeWeixinConfigManager.query();
		WxPayService wxPayService = new WxPayServiceImpl();
		if(Check.notNullOrEmpty(list)){
			Map<String, WxPayConfig> map = new HashMap<String, WxPayConfig>();
			for (StoreWeixinConfig storeWeixinConfig : list) {
				WxPayConfig payConfig = new WxPayConfig();
				payConfig.setAppId(storeWeixinConfig.getAppId());
				payConfig.setMchId(storeWeixinConfig.getMchId());
				payConfig.setMchKey(storeWeixinConfig.getMchKey());
				payConfig.setNotifyUrl(storeWeixinConfig.getNotifyUrl());
				payConfig.setKeyPath(storeWeixinConfig.getKeyPath());
				payConfig.setSignType("MD5");
				payConfig.setIfSaveApiData(true);
				map.put(storeWeixinConfig.getMchId(), payConfig);
			}
			wxPayService.setMultiConfig(map);
		}
		return wxPayService;
	}
	
	@Bean
	public EntPayService entPayService() {
		EntPayService entPayService = new EntPayServiceImpl(null);
		return entPayService;
	}
}
